const Koa = require('koa');
const Router = require('koa-router');
const VueServerRender = require('vue-server-renderer');
const path = require('path')
const fs = require('fs')
const static = require('koa-static')
const app = new Koa();
const router = new Router();

const serverBundle = fs.readFileSync(path.resolve(__dirname,'dist/server.bundle.js'),'utf8')//保证每个vue实例是单独的
const template = fs.readFileSync(path.resolve(__dirname,'dist/server.html'),'utf8')
const render =VueServerRender.createBundleRenderer(serverBundle,{template})

router.get('/',async(ctx)=>{
    ctx.body=await new Promise((resolve,reject)=>{
        render.renderToString((err,html)=>{
            if(err)reject(err);
            resolve(html)
        })
    })
})
router.get('/(.*)',async ctx=>{
    ctx.body = await new Promise(resolve => {
        render.renderToString({ url: ctx.url }, (err, html) => {
            if (err && err.code == 404) resolve(`not found`);
          // 必须写成回调函数的方式否则样式不生效
          resolve(html);
        });
      });
})

app.use(static(path.resolve(__dirname,'dist')))
app.use(router.routes());
app.listen(3000);